#include "Piece.h"
#include "Echiquier.h"
#include "Position.h"

#include <stdexcept>
#include <string>
#include <list>

using std::list;
using std::string;
using std::invalid_argument;

void test(const std::string& e)
{
	std::cout << e << std::endl;
}

Piece::Piece(Echiquier* chess,const Position& pos,bool color)
:e(chess),p(pos),c(color),cloue(false)
{}

const Position& Piece::getPosition()const
{
	return p;
}

Position& Piece::getPosition()
{
	return p;
}

const list<Position>& Piece::getDep() const
{
	return dep;
}

list<Position>& Piece::getDep()
{
    return dep;
}

bool Piece::estBlanc()const
{
	return c;
}

void Piece::deplacement(const Position& pos) throw (invalid_argument)
{
	if(!deplacementValide(pos))
		throw invalid_argument(string("La piece ") + toString() + (estBlanc() ? " blanc" : " noir") +
			string(" ne peut pas etre deplacee de ") + getPosition().toString() +
			string(" vers ") + pos.toString());
	if(e->getPiece(pos) != NULL)
		e->prisePiece(e->getPiece(pos));
	p = pos;
}

void Piece::setCloue(bool cl)
{
    cloue = cl;
}

bool Piece::getCloue() const
{
    return cloue;
}

list<Position>& Piece::getAtk()
{
	return atk;
}

void Piece::majpAtk()
{
	bool trouve;
	pAtk.clear();
	list<Piece*> l(e->getPieces(!c));
	list<Position> pos;
	for(list<Piece*>::iterator i(l.begin()); i != l.end(); i++)
	{
		trouve = false;
		pos = (*i)->getAtk();
		for(list<Position>::iterator _p(pos.begin()); _p != pos.end() && !trouve; _p++)
		{
			if(trouve = (p == *_p))
			{
				pAtk.push_back(*i);
			}
		}
	}

}

void Piece::majpDef()
{
	bool trouve;
	pDef.clear();
	for(list<Piece*>::iterator i(e->getPieces(c).begin()); i != e->getPieces(c).end(); i++)
	{
		trouve = false;
		for(list<Position>::iterator _p((*i)->getAtk().begin()); _p != (*i)->getAtk().end() && trouve; _p++)
			if(trouve = p == *_p)
				pAtk.push_back(*i);
	}
}

bool Piece::deplacementValide(const Position& p)
{
	for(list<Position>::iterator i(dep.begin()); i != dep.end(); i++)
		if(p == (*i))
			return true;

	return false;
}

const std::list<Piece*>& Piece::getpAtk() const{ return pAtk;}
const std::list<Piece*>& Piece::getpDef() const{ return pDef;}
std::list<Piece*>& Piece::getpAtk() { return pAtk;}
std::list<Piece*>& Piece::getpDef() { return pDef;}
